package com.example.batchprocessing;

import com.example.batchprocessing.entity.People;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
 * The last bit of batch configuration is a way to get notified when the job completes.
 * The following example (from src/main/java/com/example/batchprocessing/JobCompletionNotificationListener.java)
 * shows such a class:
 * */
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {

	private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);

	private final JdbcTemplate jdbcTemplate;

	@Autowired
	public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void afterJob(JobExecution jobExecution) {
		//监听到job completed
		if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
			log.info("!!! JOB FINISHED! Time to verify the results");

			jdbcTemplate.query("SELECT person_id, first_name, last_name FROM people",
				(rs, row) -> new People(
					rs.getInt(1),
					rs.getString(2),
					rs.getString(3))
			).forEach(people -> log.info("Found <" + people + "> in the database."));
		}
	}
}
